package first.codeTop.tencent;

/**
 * @ClassName LC8
 * @description:
 * @author: 荣燊
 * @create: 2021-10-25 16:32
 **/
public class LC8 {
    // 字符串转换整数 (atoi)
    public static void main(String[] args) {
        String s = "-91283472332";
        System.out.println(myAtoi(s));
    }

    // 2147483647  ,   -2147483648
    public static int myAtoi(String s) {
        int res = 0;
        char[] chars = s.toCharArray();
        // 正负号
        int flag = 1;
        // 读取的指针
        int index = 0;
        // 1.签到空格
        while (index < chars.length && chars[index] == ' ') {
            index++;
        }
        // 2.正负号
        if (index < chars.length && chars[index] == '-') {
            flag = 0;
            index++;
        }else if (index < chars.length && chars[index] == '+') {
            index++;
        }
        // 3.开始读取数字
        while (index < chars.length && chars[index] >= '0' && chars[index] <= '9') {
            if (flag == 1) {
                if (res > 214748364 || (res == 214748364 && chars[index] > '7')) {
                    return 2147483647;
                } else {
                    res = res * 10 + (chars[index]-'0');
                }
            } else {
                if (res > 214748364 || (res == 214748364 && chars[index] > '8')) {
                    return -2147483648;
                } else {
                    res = res * 10 + (chars[index]-'0');
                }
            }
            index++;
        }
        return flag == 1 ? res : res*-1;
    }

}
